package com.zztl.infiniteBand.presenter

import android.content.Context
import android.graphics.Bitmap
import com.google.zxing.BinaryBitmap
import com.google.zxing.DecodeHintType
import com.google.zxing.RGBLuminanceSource
import com.google.zxing.Result
import com.google.zxing.common.HybridBinarizer
import com.google.zxing.qrcode.QRCodeReader
import com.zztl.infiniteBand.base.BasePresenter
import com.zztl.infiniteBand.model.CheckAddressBean
import com.zztl.infiniteBand.net.FilterSubscriber
import com.zztl.infiniteBand.net.RetorfitServiceManger
import com.zztl.infiniteBand.net.converter.DataConverter
import com.zztl.infiniteBand.net.requestBean.CheckAddressRequest
import com.zztl.infiniteBand.ui.view.mvpview.ScanView
import java.util.*

/**
 * @desc
 * @auth ${user}
 * @time 2018/6/13  14:31
 */
class ScanPresenter : BasePresenter<ScanView>() {
    /**
     * 检查扫码结果是否为有效地址
     */
    fun checkResult(result: String, context: Context) {
        val request = CheckAddressRequest("InfiniteBand000001", result)
        addSubscribe(RetorfitServiceManger
                .observe(RetorfitServiceManger.instance!!.apiService
                        .checkAddress(DataConverter.instance.toJson(request)))
                .subscribe(object : FilterSubscriber<CheckAddressBean>(context) {
                    override fun success(checkAddressBean: CheckAddressBean) {
                        if (checkAddressBean.data!!.result == "true") {
                            view!!.checkSuccess(true)
                        } else {
                            view!!.checkSuccess(false)
                        }
                    }


                }))
    }


    /**
     * 扫描二维码图片的方法
     *
     * @param bitmap
     * @return
     */
    fun scanningImage(bitmap: Bitmap): Result? {
        val hints = Hashtable<DecodeHintType, String>()
        hints[DecodeHintType.CHARACTER_SET] = "UTF8" //设置二维码内容的编码

        val data = IntArray(bitmap.width * bitmap.height)
        bitmap.getPixels(data, 0, bitmap.width, 0, 0, bitmap.width, bitmap.height)
        val source = RGBLuminanceSource(bitmap.width, bitmap.height, data)
        val bitmap1 = BinaryBitmap(HybridBinarizer(source))
        val reader = QRCodeReader()
        try {
            return reader.decode(bitmap1, hints)
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return null
    }

}
